package net.cardgame.orcalecard;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.NoSuchPaddingException;

import jp.jma.oraclecard.MyApplication;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.BitmapCacheableImageView;
import net.cardgame.orcalecard.bean.DeckBean;
import net.cardgame.orcalecard.bean.SettingApp;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.FileUtils;
import uk.co.senab.bitmapcache.BitmapLruCache;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GalleryActivity extends Activity implements OnItemClickListener,
		OnItemSelectedListener, OnClickListener {

	int indexTypeHelp = 7;
	// List path các ảnh đã mã hóa
	public List<String> listPaths = new ArrayList<String>();
	private int deckID = 10;
	private String deckName = "";
	private String key = "";

	// Text mo ta bo bai
	String strDescriptionDeck = "";

	BitmapCacheableImageView iv_bg;
	TextView tvlabel_gallery;

	Button btnHelp;
	Button btnBack;

	private GalleryFlow gallery;
	private GalleryAdapter adapter;
	ArrayList<DeckBean> listSpecial;
	Handler handler = new Handler();
	TextView tv_name;
	public static String pathCardBackImage = "";
	SecurePreferences appPreferences;
	private SecurePreferences contentPreferences;
	SettingApp setting;
	int deckId = 0;
	int cardId = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_gallery);
		iv_bg = (BitmapCacheableImageView) findViewById(R.id.iv_bg);
		gallery = (GalleryFlow) findViewById(R.id.gallery);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tvlabel_gallery = (TextView) findViewById(R.id.tvlabel_gallery);

		//
		getListSpecial();
		//

		Bundle bundle = this.getIntent().getExtras();
		deckID = bundle.getInt("deckId");
		// deckName = bundle.getString("deckName");

		// tvlabel_gallery.setText(deckName);
		contentPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		threadLoadTitleGallery loadTitle = new threadLoadTitleGallery();
		loadTitle.start();

		// Neu khong phai bo Special
		if (deckID != 999) {
			String strDECKID = (deckID < 10) ? ("0" + deckID) : ("" + deckID);
			pathCardBackImage = ConstantValue.APP_PREFERENCES + "/Card_"
					+ strDECKID + "/en_c" + strDECKID + "d.png";
		} else { // Neu la bo Special
			if (!listSpecial.isEmpty()) {
				iv_bg.setImageResource(R.drawable.bg999);
				tvlabel_gallery.setText(R.string.name_special_deck);
			}
		}

		new loadPathsAsyncTask().execute();

		gallery.setOnItemClickListener(this);
		gallery.setOnItemSelectedListener(this);
		btnHelp = (Button) findViewById(R.id.btnHelp);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnHelp.setOnClickListener(this);
		btnBack.setOnClickListener(this);
	}

	class threadLoadTitleGallery extends Thread {
		public void run() {
			handler.post(new Runnable() {

				@Override
				public void run() {
					key = "content_" + deckID;
					if (contentPreferences.containsKey(key)) {
						deckName = contentPreferences.getString(key);
						String[] arr = deckName.split("---");
						deckName = arr[0];
						if (deckName.contains("←"))
							deckName = deckName.substring(0,
									deckName.indexOf("←"));
						tvlabel_gallery.setText(deckName);
					}
				}
			});
		}
	}

	void loadSettingApp() {
		Gson gson = new Gson();
		Type SettingAppType = new TypeToken<SettingApp>() {
		}.getType();
		if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) {
			String strSetting = appPreferences
					.getString(ConstantValue.SETTING_KEY);
			setting = gson.fromJson(strSetting, SettingAppType);
		}

	}

	ArrayList<DeckBean> getListSpecial() {
		appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		loadSettingApp();
		Gson gson = new Gson();
		Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() {
		}.getType();
		String listSaved = appPreferences
				.getString(ConstantValue.CONFIG_DECKBEAN_KEY);
		ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved,
				listOfDeckBean);
		listSpecial = new ArrayList<DeckBean>();
		for (DeckBean deckBean : listDeckBean) {
			if (deckBean.percentDownloaded == -2 && deckBean.deckId != 999
					&& deckBean.deckId != 998
					&& setting.listSpecial.contains((Integer) deckBean.deckId)) {
				listSpecial.add(deckBean);
			}
		}
		return listSpecial;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent i = new Intent(this, CardDetailActivity.class);
		deckId = dId;
		cardId = cId;
		i.putExtra("cardId", cardId);
		i.putExtra("deckId", deckId);
		startActivityForResult(i, 1);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		clearCacheCardDetail();
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		String[] content = getContentCard(position).split("---");
		String title = content[0];

		for (int i = 0; i < title.length() - 1; i++) {
			if (title.charAt(i) == '←') {
				title = title.substring(0, i - 1);
				break;
			}
		}
		tv_name.setText(title);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnBack:
			goBack();
			break;
		case R.id.btnHelp:
			onClickButtonHelp();
		default:
			break;
		}
	}

	public void onClickButtonHelp() {
		Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class);
		i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp);
		startActivity(i);
	}

	public String getContentCard(int pos) {
		String fullPath = listPaths.get(pos);
		Detect_DeckId_CardId_FromPath(fullPath);
		int deckId = dId;
		int cardId = cId;
		byte[] bytes;

		String strDECKID = (deckId < 10) ? ("0" + deckId) : ("" + deckId);
		String strCARDID = (cardId < 10) ? ("0" + cardId) : ("" + cardId);

		String content = "";
		String pathTextFile = ConstantValue.getPatchCardData(this) + "/Card_"
				+ strDECKID + "/en_t" + strDECKID + strCARDID + ".txt";

		try {
			bytes = FileUtils.decryptToByteArray(pathTextFile, "");
			content = new String(bytes, "UTF-8"); // Va ma hoa ve utf-8
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return content;
	}

	public void loadImageBackground(int _deckID) {
		String strDECKID = (_deckID < 10) ? ("0" + _deckID) : ("" + _deckID);

		// Path toi file anh background
		String pathImageBackground = ConstantValue.getPatchCardData(this)
				+ "Card_" + strDECKID + "/en_bg" + strDECKID + ".jpg";

		iv_bg = (BitmapCacheableImageView) findViewById(R.id.iv_bg);
		iv_bg.loadImage(pathImageBackground, this, 0);
	}

	private class loadPathsAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// Neu khong phai deck Special
			if (deckID != 999) {
				listPaths = loadPaths(deckID, "png");
			} else { // Neu la deck Special
				for (DeckBean dec : listSpecial) {
					List<String> temp = new ArrayList<String>();
					temp = loadPaths(dec.deckId, "png");
					if (temp.size() > 0) {
						for (String p : temp) {
							listPaths.add(p);
						}
					}
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (deckID != 999) {
				loadImageBackground(deckID);
				adapter = new GalleryAdapter(GalleryActivity.this, listPaths,
						false);
			} else
				adapter = new GalleryAdapter(GalleryActivity.this, listPaths,
						true);

			gallery.setAdapter(adapter);
			gallery.setSpacing(-100);
			super.onPostExecute(result);
		}
	}

	public List<String> loadPaths(int deckId, String strFilter) {
		String strDECKID = (deckId < 10) ? "0" + deckId : "" + deckId;
		String _pathDirectory = ConstantValue.getPatchCardData(this) + "Card_"
				+ strDECKID + "/X2/";

		String strFilter1 = "c" + strDECKID + "t1-3";
		String strFilter2 = "c" + strDECKID + "t";
		String strFilter3 = "c" + strDECKID + "s";
		String strFilter4 = "c" + strDECKID + "p";
		String strFilter5 = "c" + strDECKID + "m";
		String strFilter6 = "c" + strDECKID + "n";
		String strFilter7 = "c" + strDECKID + "i";
		String strFilter8 = "c" + strDECKID + "j";
		String strFilter9 = "c" + strDECKID + "d";
		String strFilter10 = "copyright";
		String strFilter11 = "c" + strDECKID + "00";

		List<String> listPaths = new ArrayList<String>();

		File targetDirector = new File(_pathDirectory);
		File[] listFiles = targetDirector.listFiles();

		if (listFiles.length > 0) {
			for (File f : listFiles) {

				String[] arr = null;
				String sub = "";
				String s = "";

				arr = f.getPath().split("\\/");
				sub = arr[arr.length - 1];

				arr = sub.split("\\.");
				sub = arr[arr.length - 1];
				s = arr[0];
				arr = s.split("\\_");
				s = arr[arr.length - 1];

				if (sub.equalsIgnoreCase(strFilter))
					if (!s.equalsIgnoreCase(strFilter1)
							&& !s.equalsIgnoreCase(strFilter2)
							&& !s.equalsIgnoreCase(strFilter3)
							&& !s.equalsIgnoreCase(strFilter4)
							&& !s.equalsIgnoreCase(strFilter5)
							&& !s.equalsIgnoreCase(strFilter6)
							&& !s.equalsIgnoreCase(strFilter7)
							&& !s.equalsIgnoreCase(strFilter8)
							&& !s.equalsIgnoreCase(strFilter9)
							&& !s.equalsIgnoreCase(strFilter10)
							&& !s.equalsIgnoreCase(strFilter11))
						listPaths.add(f.getPath());
			}
			java.util.Collections.sort(listPaths);
		}
		return listPaths;
	}

	private int dId = -1;
	private int cId = -1;

	public void Detect_DeckId_CardId_FromPath(String path) {
		String[] arrPath = null;
		String subPath1 = "";
		String subPath2 = "";

		arrPath = path.split("\\/");
		subPath1 = arrPath[arrPath.length - 3];
		subPath2 = arrPath[arrPath.length - 1];

		arrPath = subPath1.split("\\_");
		subPath1 = arrPath[arrPath.length - 1];
		subPath2 = subPath2.substring(6, 8);

		dId = Integer.parseInt(subPath1);
		cId = Integer.parseInt(subPath2);

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		goBack();
	}

	void goBack() {
		Intent intent = new Intent(this, CardDeckActivity.class);
		intent.putExtras(getIntent().getExtras());
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		this.finish();
	}

	void clearCacheCardDetail() {
		BitmapLruCache cache = MyApplication.getInstance().getBitmapCache();
		cache.removeFromMemory(ConstantValue.getPathCardDetail(this, deckId,
				cardId, ConstantValue.X1));
	}

	void setFontTextView(TextView tv, String patch) {
		Typeface type = Typeface.createFromAsset(getAssets(), patch);
		tv.setTypeface(type);
	}
}
